import { Component, OnInit } from '@angular/core';
import { UntypedFormBuilder, Validators, UntypedFormGroup } from '@angular/forms';
import { Router } from '@angular/router';
import { _HttpClient } from '@delon/theme';
import { NzMessageService } from 'ng-zorro-antd/message';
import { Api } from 'src/app/shared/api/api';
import { ResponseCode } from 'src/app/shared/response.code';

@Component({
  selector: 'passport-forgot',
  templateUrl: './forgot.component.html',
  styleUrls: ['./forgot.component.less']
})
export class ForgotComponent implements OnInit {
  kaptcha: any = null;
  constructor(fb: UntypedFormBuilder, private router: Router, public http: _HttpClient, public msg: NzMessageService) {
    this.form = fb.group({
      email: [null, [Validators.required, Validators.email]],
      code: [null, [Validators.required]]
    });
  }
  get code() {
    return this.form.controls['code'];
  }
  get email() {
    return this.form.controls['email'];
  }
  form: UntypedFormGroup;
  error = '';

  count = 0;
  interval$: any;

  ngOnInit(): void {
    this.getKaptch();
  }

  getKaptch() {
    this.kaptcha = `${Api.KaptchaApi}&time=${new Date().getMilliseconds()}`;
  }

  submit(): void {
    this.error = '';
    Object.keys(this.form.controls).forEach(key => {
      this.form.controls[key].markAsDirty();
      this.form.controls[key].updateValueAndValidity();
    });
    if (this.form.invalid) {
      return;
    }
    const data = this.form.value;
    this.http
      .post(
        `${Api.ForgotPasswordApi}&code=${data.code}&email=${data.email}`,
        {},
        {},
        {
          headers: {
            'Content-Type': 'application/json',
            Authorization: 'Basic dGVzdDp0ZXN0'
          }
        }
      )
      .subscribe(
        res => {
          if (res) {
            if (res.code === ResponseCode.SUCCESS) {
              this.router.navigate(['/passport/reset'], { queryParams: { email: data.email } });
            } else {
              this.getKaptch();
              this.error = res.data;
            }
          } else {
            this.getKaptch();
            this.error = '找回失败，未知原因！';
          }
        },
        error => {
          console.log(error);
          this.msg.error('找回失败');
        }
      );
  }
}
